
from sqlalchemy.orm import *
from sqlalchemy.types import * 
from sqlalchemy import create_engine
from typing import Optional
from sqlalchemy import select
from utils import log as F


class Base(DeclarativeBase):
    def _asdict(self):
        return {column.name: getattr(self, column.name) for column in self.__table__.columns}

class sport(Base):
    __tablename__="sport"
    id : Mapped[Integer] = mapped_column( Integer, nullable=False,primary_key=True, autoincrement=True, ) 
    name : Mapped[String] = mapped_column( String,  ) 
    cate : Mapped[String] = mapped_column( String,  ) 
    content : Mapped[String] = mapped_column( String,  ) 
    pic : Mapped[String] = mapped_column(String,)




def select_all(engine):
    with Session(engine) as session :
        return [rec._asdict() for rec in session.query(sport).all()]
    
def select_by_col(engine,cond:dict):
    with Session(engine) as session :
        return [rec._asdict() for rec in session.query(sport).filter_by(**cond).all()]


def update_one(engine,cond:dict,item:dict):
    with Session(engine) as session:
        record = session.query(sport).filter_by(**cond).first()
        if record:
            # Update the record with the new values
            for key, value in item.items():
                setattr(record, key, value)
            session.commit()
            return True
        return False 
    
def add_one(engine,item:dict):
    try:
        with Session(engine) as session :
            record = sport(**item)
            session.add(record)
            session.commit()
            return True 
    except Exception as e:
        print(e)
        return False
    
def delete_one(engine,cond:dict):
    try:
        with Session(engine) as session :
            record = session.query(sport).filter_by(**cond).first()
            session.delete(record)
            session.commit()
            try:
                record = session.query(F.log).filter_by(sport_id=cond['id']).all()
                for rec in record:
                    session.delete(rec)
                session.commit()
            except Exception as e:
                print(e)
            return True 
    except Exception as e:
        return False  
def delete_batch(engine,cond:dict):
    try:
        with Session(engine) as session :
            records = session.query(sport).filter_by(**cond).all()
            for rec in records:
                session.delete(rec)
            session.commit()
            return True 
    except Exception as e:
        return False  
